<template>
  <div id="edit-goods" :spinning="loading">
    <u-panel title="编辑商品">
      <template slot="action-items">
        <a-button type="primary" @click="handleToList" ghost>返回列表</a-button>
      </template>
    </u-panel>
    <div>
      <a-spin :spinning="loading">
        <a-form
          id="components-form-demo-validate-other"
          :form="form"
          @submit="handleSubmit"
        >
          <a-form-item v-bind="formItemLayout" label="商品分类" has-feedback>
            <a-tree-select
              v-decorator="formData.type_id"
              style="width: 150px"
              allowClear
              :treeData="typeTree"
              placeholder="请选择类型"
              treeDefaultExpandAll
            >
            </a-tree-select>
          </a-form-item>

          <a-form-item v-bind="formItemLayout" label="商品名称" has-feedback>
            <a-input
              v-decorator="formData.name"
              placeholder="商品名称"
            ></a-input>
          </a-form-item>
          <a-form-item v-bind="formItemLayout" label="状态">
            <a-switch
              v-decorator="formData.status"
              checkedChildren="上架"
              unCheckedChildren="下架"
            ></a-switch>
          </a-form-item>

          <a-form-item v-bind="formItemLayout" label="商品封面">
            <a-upload
              :beforeUpload="beforeUpload"
              @change="handleChange"
              class="img-uploader"
              name="img"
              listType="picture-card"
              :showUploadList="false"
              :action="uploadUrl"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                alt="avatar"
                style="width:128px;height:128px"
              />
              <div v-else>
                <a-icon :type="imgLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="描述" v-bind="formItemLayout">
            <tinymce-editor v-model="desc"></tinymce-editor>
          </a-form-item>
          <a-divider orientation="left">Sku</a-divider>
          <a-row>
            <a-col :span="14" :offset="6">
              <u-skus v-model="sku" :validate="skuValidate"></u-skus>
            </a-col>
          </a-row>

          <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
            <a-button type="primary" html-type="submit">
              保存
            </a-button>
          </a-form-item>
        </a-form>
      </a-spin>
    </div>
  </div>
</template>

<script>
import UPanel from "@/components/Panel/Panel";
import USkus from "./components/sku";
import { fetchSelectTree } from "@/api/goodsType";
import { updateGoods, fetchInfo } from "@/api/goods";
import TinymceEditor from "@/components/Form/TinymceEditor";
export default {
  components: {
    UPanel,
    USkus,
    TinymceEditor
  },
  data: () => ({
    id: 0,
    loading: true,
    imgLoading: false,
    typeTree: [],
    formItemLayout: {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 }
    },
    imageUrl: "",
    uploadUrl: process.env.VUE_APP_UPLOAD_URL,
    sku: [],
    desc: "",
    skuValidate: {
      status: "success",
      field: "sku",
      errorMsg: ""
    },
    formData: {
      type_id: [
        "type_id",
        {
          rules: [{ required: true, message: "请选择商品分类!" }]
        }
      ],
      name: [
        "name",
        {
          rules: [{ required: true, message: "请输入商品名称!" }]
        }
      ],
      status: [
        "status",
        {
          required: true,
          valuePropName: "checked",
          initialValue: true
        }
      ]
    }
  }),
  created() {
    this.id = this.$route.params.id;
    fetchInfo(this.id).then(res => {
      this.loading = false;
      const data = res.data;
      this.imageUrl = data.thumb;
      this.formData.type_id[1].initialValue = data.type_id + "";
      this.formData.name[1].initialValue = data.name;
      this.formData.status[1].initialValue = data.status;
      this.desc = data.desc;
      this.sku = data.sku;
    });
    this.fetchSelectTree();
  },
  beforeCreate() {
    this.form = this.$form.createForm(this);
  },
  methods: {
    handleToList() {
      this.$router.replace("/goods/index");
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        values.thumb = this.imageUrl;
        values.sku = this.sku;
        values.desc = this.desc;
        if (!err) {
          this.loading = true;
          updateGoods(values, this.id)
            .then(res => {
              this.loading = false;
              if (res.code === 1) {
                this.handleToList();
              }
            })
            .catch(error => {
              this.loading = false;
              if (error.response.status === 422) {
                for (var i in error.errorBag) {
                  if (i.split(".")[0] === "sku") {
                    this.skuValidate = {
                      status: "error",
                      errorMsg: error.errorBag[i].errors[0].message,
                      field: i
                    };
                  } else {
                    this.$common.validateExtend(error, this.form);
                  }
                }
              }
              return true;
            });
        }
      });
    },
    fetchSelectTree() {
      fetchSelectTree().then(res => {
        let $data = res.data;
        $data = this.tree($data);

        this.typeTree = $data;
      });
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e;
      }
      if (e.fileList.length > 0) {
        return e && e.fileList;
      }
    },
    tree(items) {
      let treeNode = [];
      items.forEach(item => {
        if (item.is_parent) {
          item.disabled = true;
          if (item.children && item.children.length) {
            item.children = this.tree(item.children);
          }
        }
        treeNode.push(item);
      });
      return treeNode;
    },
    handleChange(info) {
      console.log(info);
      if (info.file.status === "uploading") {
        this.imgLoading = true;
        return;
      }
      if (info.file.status === "done") {
        // Get this url from response in real world.
        this.$common.getBase64(info.file.originFileObj, () => {
          const res = info.file.response;
          this.imageUrl = res.code === 1 ? res.data.url : "";
          this.imgLoading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      if (!isJPG) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="less" scoped>
.img-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
